package mq.rabbitmq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

public class Router {
    public final static String QUEUE_NAME_GT0_LT10 = "gt0lt10_queue";
    public final static String QUEUE_NAME_GT10 = "gt10_queue";
    public final static String ROUTER_KEY_GT0_LT10 = "gt0lt10";
    public final static String ROUTER_KEY_GT10 = "gt10";
    public final static String EXCHANGE_NAME = "gt_router";
    public final static String HOST = "47.101.147.181";
    public final static String USERNAME = "root";
    public final static String PASSWORD = "root";
    public final static ConnectionFactory factory = new ConnectionFactory();
    static {
        factory.setHost(HOST);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
    }
    public static void publicMsg() throws IOException, TimeoutException, InterruptedException {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        int j = 0;
        while (j<20){
            j++;
            Random random = new Random();
            int i = random.nextInt(20);
            String msg = i+"";
            String routerKey;
            if (i > 10){
                routerKey = ROUTER_KEY_GT10;
            }else {
                routerKey = ROUTER_KEY_GT0_LT10;
            }
            channel.basicPublish(EXCHANGE_NAME,routerKey,null,msg.getBytes());
            System.out.println("发送消息："+msg+"路由："+routerKey);
            Thread.sleep(1000);
        }
    }

    public static void subscribe(String queueName,String routerKey) throws IOException, TimeoutException {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        channel.queueDeclare(queueName,false,false,false,null);
        channel.queueBind(queueName,EXCHANGE_NAME,routerKey);
        channel.basicQos(1);
        channel.basicConsume(queueName,false,(consumerTag, message) -> {
            System.out.printf("订阅队列%s:%s%n",queueName,new String(message.getBody(),"UTF-8"));
            channel.basicAck(message.getEnvelope().getDeliveryTag(),true);
        },consumerTag ->{});

    }

    public static void main(String[] args) {
        new Thread(()->{
            try {
                publicMsg();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }

}
